package com.zw.yzk.kabu.view.activity;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v4.graphics.ColorUtils;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;

import butterknife.Bind;
import butterknife.OnClick;

import com.bumptech.glide.Glide;
import com.zw.yzk.kabu.R;
import com.zw.yzk.kabu.adapter.CosDetailsCommentAdapter;
import com.zw.yzk.kabu.adapter.CosDetailsImageAdapter;
import com.zw.yzk.kabu.base.BaseActivity;
import com.zw.yzk.kabu.constant.ActivityConstant;
import com.zw.yzk.kabu.internal.component.DaggerCosplayDetailsComponent;
import com.zw.yzk.kabu.internal.module.*;
import com.zw.yzk.kabu.management.LoadingDialogManager;
import com.zw.yzk.kabu.management.ToolbarBuilder;
import com.zw.yzk.kabu.model.CosDetailsCommentModel;
import com.zw.yzk.kabu.model.CosDetailsImageModel;
import com.zw.yzk.kabu.presenter.CosplayDetailsPresenter;
import com.zw.yzk.kabu.utils.CircleTransform;
import com.zw.yzk.kabu.utils.PhoneUtils;
import com.zw.yzk.kabu.utils.StringUtils;
import com.zw.yzk.kabu.utils.TimeFormatUtils;
import com.zw.yzk.kabu.view.view.CosDetailsView;
import com.zw.yzk.kabu.view.widget.CommentDialog;
import com.zw.yzk.kabu.view.widget.MyScrollView;

import skin.support.content.res.SkinCompatResources;

import javax.inject.Inject;

import java.util.List;

/**
 * Created by zhanwei on 2017/1/15.
 */

public class CosplayDetailsActivity extends BaseActivity implements CosDetailsView, CosDetailsCommentAdapter.OnCommentClickedListener {

    View toolBar;
    @Bind(R.id.scroll_view)
    MyScrollView scrollView;
    @Bind(R.id.time)
    TextView time;
    @Bind(R.id.name)
    TextView name;
    @Bind(R.id.head)
    ImageView head;
    @Bind(R.id.image_list)
    RecyclerView imageList;
    @Bind(R.id.comment_title)
    TextView commentTitle;
    @Bind(R.id.comment_list)
    RecyclerView commentList;
    @Bind(R.id.action_layout)
    View actionLayout;
    @Bind(R.id.collect)
    CheckBox collect;
    @Bind(R.id.praise)
    CheckBox praise;
    @Bind(R.id.concern)
    CheckBox concern;
    @Bind(R.id.top_content)
    TextView topContent;
    @Bind(R.id.top_bg)
    ImageView topBg;
    @Bind(R.id.describe)
    TextView describe;
    @Bind(R.id.layout_vote)
    View voteLayout;
    @Bind(R.id.vote)
    CheckBox vote;
    @Bind(R.id.layout_vote_info)
    View voteInfoLayout;
    @Bind(R.id.ranking)
    TextView ranking;
    @Bind(R.id.ballot)
    TextView ballot;

    @Inject
    CosplayDetailsPresenter presenter;
    private CosDetailsImageAdapter cosImageAdapter;
    private CosDetailsCommentAdapter cosCommentAdapter;
    private CommentDialog commentDialog;
    private int cosplayId;
    private int publisherId;

    @Override
    public int getLayoutId() {
        PhoneUtils.setStatusBarColor(CosplayDetailsActivity.this, ContextCompat.getColor(this, R.color.transparent));
        return R.layout.activity_cosplay_details;
    }

    @Override
    public void iniToolbar(BaseActivity activity) {
        String title = getIntent().getStringExtra(ActivityConstant.OPEN_COS_DETAIL_NAME);
        if (TextUtils.isEmpty(title)) {
            title = getResources().getString(R.string.details);
        }
        toolBar = ToolbarBuilder
                .createBuilder(this)
                .setBackgroundColor(ContextCompat.getColor(this, R.color.transparent))
                .setTitle(title)
                .build();

        PhoneUtils.setViewMarginTopStatusBarHeight(this, toolBar);
    }

    @Override
    public void initComponent() {
        DaggerCosplayDetailsComponent.builder()
                .applicationComponent(getApplicationComponent())
                .activityModule(new ActivityModule(this))
                .cosplayDetailsModule(new CosplayDetailsModule())
                .commentModule(new CommentModule())
                .getCommentModule(new GetCommentModule())
                .followModule(new FollowModule())
                .build()
                .inject(this);
        presenter.setView(this);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        init();
    }

    @Override
    protected boolean skinStatusBarColorEnable() {
        return false;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (presenter != null) {
            presenter.destroy();
        }
    }

    @Override
    public void setHead(String head) {
        Glide.with(this)
                .load(head)
                .placeholder(R.drawable.ic_default_head)
                .error(R.drawable.ic_default_head)
                .transform(new CircleTransform(this))
                .into(this.head);
    }

    @Override
    public void setNickName(String nickName) {
        if (!TextUtils.isEmpty(nickName)) {
            name.setText(nickName);
        }
    }

    @Override
    public void setDate(String date) {
        try {
            time.setText(TimeFormatUtils.getTimeInterval(date, "yyyy-MM-dd HH:mm:ss"));
        } catch (Exception e) {
            time.setText(date);
        }
    }

    @Override
    public void setDescribe(String d) {
        if (TextUtils.isEmpty(d)) {
            return;
        }
        describe.setText(d);
    }

    @Override
    public void setImageList(List<CosDetailsImageModel> list) {
        if (cosImageAdapter == null) {
            cosImageAdapter = new CosDetailsImageAdapter(list);
            imageList.setAdapter(cosImageAdapter);
        } else {
            cosImageAdapter.refresh(list);
        }
    }

    @Override
    public void setCommentList(List<CosDetailsCommentModel> list) {
        if (cosCommentAdapter == null) {
            cosCommentAdapter = new CosDetailsCommentAdapter(list);
            cosCommentAdapter.setOnCommentClickedListener(this);
            commentList.setAdapter(cosCommentAdapter);
        } else {
            cosCommentAdapter.refresh(list);
        }
    }

    @Override
    public void addCommentList(List<CosDetailsCommentModel> commentList) {
        cosCommentAdapter.add(commentList);
        //向下滑动100个像素，将新加载出的item显示出来
        scrollView.smoothScrollBy(0, 100);
    }

    @Override
    public void setTopImage(String image) {
        Glide.with(this)
                .load(image)
                .into(topBg);
    }

    @Override
    public void showActionLayout() {
        actionLayout.setVisibility(View.VISIBLE);
    }

    @Override
    public int getCosplayId() {
        return cosplayId;
    }

    @Override
    public int getCommentCount() {
        return cosCommentAdapter.getItemCount();
    }

    @Override
    public boolean getPraiseState() {
        return praise.isChecked();
    }

    @Override
    public void praiseFialed() {
        praise.setChecked(!praise.isChecked());
    }

    @Override
    public boolean getCollectState() {
        return collect.isChecked();
    }

    @Override
    public void collectFailed() {
        collect.setChecked(!collect.isChecked());
    }

    @Override
    public boolean getFollowState() {
        return concern.isChecked();
    }

    @Override
    public void followFailed() {
        setConcernBtnStatus(!concern.isChecked());
    }

    @Override
    public void setPraiseAndCollectStatus(boolean p, boolean c, boolean f) {
        collect.setChecked(c);
        praise.setChecked(p);
        setConcernBtnStatus(f);
    }

    @Override
    public void setTopContent(String content) {
        topContent.setText(content);
        //设置文本样式
        SpannableString string = colorTextAndClickableWithPattern(
                content, StringUtils.DIVIDE_STRING_PATTERN1,
                ContextCompat.getColor(this, R.color.gold), this);
        SpannableString text = colorTextAndClickableWithPattern(
                string, StringUtils.DIVIDE_STRING_PATTERN2,
                ContextCompat.getColor(this, R.color.gold), this);
        topContent.setText(text);
        topContent.setMovementMethod(LinkMovementMethod.getInstance());
        topContent.setHighlightColor(ContextCompat.getColor(this, R.color.transparent));
        if (TextUtils.isEmpty(content)) {
            topContent.setVisibility(View.GONE);
        }
    }

    @Override
    public void setPublisherId(int id) {
        publisherId = id;
    }

    @Override
    public void setTotalCommentCount(int count) {
        commentTitle.setText(getResources().getString(R.string.latest_comment_with_count, count));
    }

    @Override
    public void showVoteInfo(boolean show, boolean isVoted, int ranking, int ballot) {
        if (show) {
            voteLayout.setVisibility(View.VISIBLE);
            vote.setText(isVoted ? R.string.voted : R.string.vote);
            vote.setChecked(isVoted);

            voteInfoLayout.setVisibility(View.VISIBLE);
            this.ranking.setText(String.valueOf(ranking));
            this.ballot.setText(String.valueOf(ballot));
        } else {
            voteLayout.setVisibility(View.GONE);
            voteInfoLayout.setVisibility(View.GONE);
        }
    }

    @Override
    public void voteSuccess() {
        vote.setChecked(true);
        vote.setText(R.string.voted);
    }

    @Override
    public void onCommentClicked(CosDetailsCommentModel model) {
        showCommentDialog(model.getCosId(), String.valueOf(model.getCommentId()));
    }

    @OnClick(R.id.layout_concern)
    public void concern() {
        setConcernBtnStatus(!concern.isChecked());
        follow();
    }

    @OnClick(R.id.layout_praise)
    public void praise() {
        praise.setChecked(!praise.isChecked());
        praiseCos();
    }

    @OnClick(R.id.comment)
    public void comment() {
        showCommentDialog(cosplayId, null);
    }

    @OnClick(R.id.layout_collect)
    public void collect() {
        collect.setChecked(!collect.isChecked());
        collectCos();
    }

    @OnClick(R.id.head)
    public void startHomePage() {
        Intent intent = new Intent(this, HomePageActivity.class);
        intent.putExtra(ActivityConstant.HOME_PAGE_ID, publisherId);
        startActivity(intent);
    }

    @OnClick(R.id.layout_vote)
    public void vote() {
        if (!vote.isChecked()) {
            presenter.vote(cosplayId);
        }
    }

    /**
     * 初始化操作
     */
    private void init() {
        initRecyclerView();
        setScrollListener();

        //获取cos详情
        cosplayId = getIntent().getIntExtra(ActivityConstant.OPEN_COS_DETAIL_ID, 0);
        getCosDetails(cosplayId);
    }

    /**
     * 设置关注按钮状态
     *
     * @param checked
     */
    private void setConcernBtnStatus(boolean checked) {
        concern.setChecked(checked);
        concern.setText(checked ? R.string.has_concerned : R.string.concern);
    }

    /**
     * 初始化RecyclerView
     */
    private void initRecyclerView() {
        imageList.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        imageList.setNestedScrollingEnabled(false);
        commentList.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        commentList.setNestedScrollingEnabled(false);
    }

    /**
     * 设置滚动监听
     */
    private void setScrollListener() {
        final int color = SkinCompatResources.getInstance().getColor(R.color.toolbar_bg);
        scrollView.setOnScrollListener(new MyScrollView.ScrollListener() {
            @Override
            public void onScroll(int dy) {
                float percent = dy / (getResources().getDimension(R.dimen.toolbar_height) * 3f);
                percent = percent > 1 ? 1 : percent;
                int bgColor = ColorUtils.setAlphaComponent(color, (int) (255 * percent));
                //int bgColor = Color.argb((int) (255 * percent), 0, 0, 0);
                toolBar.setBackgroundColor(bgColor);
                PhoneUtils.setStatusBarColor(CosplayDetailsActivity.this, bgColor);

                if (cosCommentAdapter.getItemCount() > 0 && dy + scrollView.getBottom() == commentList.getBottom()) {
                    //已经滑动到距离底部，开始加载更多
                    int count = cosCommentAdapter.getItemCount();
                    getCommentList(count, cosplayId, cosCommentAdapter.getDataList().get(count - 1).getCommentId());
                }
            }
        });
    }

    /**
     * 显示评论对话框
     */
    private void showCommentDialog(final int cosId, final String replayId) {
        if (commentDialog == null) {
            commentDialog = new CommentDialog(this);
        }
        commentDialog.setOnSendClickedListener(new CommentDialog.OnSendClickedListener() {
            @Override
            public void onClick(View v) {
                commentCosplay(cosId, replayId, commentDialog.getComment());
            }
        });
        commentDialog.showDialog(findViewById(android.R.id.content));
        //弹出软键盘
        InputMethodManager imm = (InputMethodManager) getSystemService(Service.INPUT_METHOD_SERVICE);
        imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
    }

    /**
     * 获取cos详情
     *
     * @param cosId cosId
     */
    private void getCosDetails(int cosId) {
        presenter.getCosDetails(cosId);
        //显示加载对话框
        LoadingDialogManager.getInstance().showLoadingDialog(this);
    }

    /**
     * 评论cos
     *
     * @param cosplayId cosId
     * @param replayId  replayId
     * @param content   内容
     */
    private void commentCosplay(int cosplayId, String replayId, String content) {
        presenter.commentCos(cosplayId, replayId, content);
        LoadingDialogManager.getInstance().showLoadingDialog(this);
    }

    /**
     * praise true：点赞，false：取消点赞
     */
    private void praiseCos() {
        presenter.praise(cosplayId, praise.isChecked());
    }

    /**
     * collect   true:收藏，false：取消收藏
     */
    private void collectCos() {
        presenter.collect(cosplayId, collect.isChecked());
    }

    /**
     * follow   true:收藏，false：取消收藏
     */
    private void follow() {
        presenter.follow(concern.isChecked());
        setConcernBtnStatus(concern.isChecked());
    }

    /**
     * 获取评论列表
     *
     * @param start     开始
     * @param cosplayId cosId
     */
    public void getCommentList(int start, int cosplayId, int lastId) {
        presenter.getCommentList(start, cosplayId, lastId);
    }

    /**
     * 给特定格式文本着色并添加点击事件
     *
     * @param source  源文本
     * @param pattern 格式
     * @param color   颜色
     * @return SpannableString
     */
    private SpannableString colorTextAndClickableWithPattern(String source, String pattern, int color, Context context) {
        if (TextUtils.isEmpty(source)) {
            return new SpannableString("");
        }
        SpannableString spanText = new SpannableString(source);
        List<String> patternResult = StringUtils.divideString(source, pattern);
        String remainString = source;
        int realStart = 0;
        for (String str : patternResult) {
            realStart += remainString.indexOf(str);
            spanText.setSpan(new ClickSpan(context), realStart, realStart + str.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            spanText.setSpan(new ForegroundColorSpan(color), realStart, realStart + str.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
            remainString = remainString.substring(remainString.indexOf(str) + str.length());
            realStart += str.length();
        }

        return spanText;
    }

    /**
     * 给特定格式文本着色并添加点击事件
     *
     * @param source  源文本
     * @param pattern 格式
     * @param color   颜色
     * @return SpannableString
     */
    private SpannableString colorTextAndClickableWithPattern(SpannableString source, String pattern, int color, Context context) {
        if (source == null) {
            return new SpannableString("");
        }
        SpannableString spanText = source;
        List<String> patternResult = StringUtils.divideString(source.toString(), pattern);
        String remainString = source.toString();
        int realStart = 0;
        for (String str : patternResult) {
            realStart += remainString.indexOf(str);
            spanText.setSpan(new ClickSpan(context), realStart, realStart + str.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            spanText.setSpan(new ForegroundColorSpan(color), realStart, realStart + str.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
            remainString = remainString.substring(remainString.indexOf(str) + str.length());
            realStart += str.length();
        }

        return spanText;
    }


    private static class ClickSpan extends ClickableSpan {

        private Context context;

        public ClickSpan(Context context) {
            this.context = context;
        }

        @Override
        public void onClick(View widget) {
            try {
                TextView tv = (TextView) widget;
                String s = tv.getText().subSequence(tv.getSelectionStart(),
                        tv.getSelectionEnd()).toString().replace("#", "");
                if (s.startsWith("@")) {
                    HomePageActivity.startHomePageActivity(context, 0, s.substring(1));
                } else {
                    TopicListActivity.startTopicActivity(context, s);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        @Override
        public void updateDrawState(TextPaint ds) {
            ds.setColor(ds.linkColor);
            ds.setUnderlineText(false);    //去除超链接的下划线
        }
    }
}
